<template>
    <div class="box">
        <el-form :model="form" size="small" :rules="rules" ref="form" label-width="120px">
            <div class="panel">
                <div class="header">基本信息</div>
                <div class="bd">
                    <div class="fm-short">
                        <el-form-item label="选择系统:" prop="sourceFrom">
                            <el-select v-model="form.sourceFrom" placeholder="请选择系统" clearable>
                                <el-option v-for="item in supplierList" :key="item.supplierCode" :label="item.supplierName" :value="item.supplierCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="产品名称:" prop="resourceName">
                            <el-input v-model="form.resourceName" placeholder="请输入产品名称  最多45个字" maxlength="45" show-word-limit></el-input>
                        </el-form-item>
                        <div  >
                            <el-form-item label="景点与票种:" prop="cityId">
                                <el-select v-model="form.cityId" placeholder="请选择景点所在的城市" filterable clearable @change="getSpotList">
                                    <el-option v-for="item in cityList" :key="item.cityId" :label="item.cityName" :value="item.cityId"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="spotId">
                                <el-select v-model="form.spotId" placeholder="请选择景区" filterable clearable>
                                    <el-option v-for="item in spotList" :key="item.spotId" :label="item.spotName" :value="item.spotId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="peopleGroup">
                                <el-select v-model="form.peopleGroup" placeholder="请选择门票票种" clearable>
                                    <el-option v-for="item in peoplesList" :key="item.id" :label="item.peopleGroupName" :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <el-form-item label="费用包含:" prop="priceContain">
                            <el-input v-model="form.priceContain"  type="textarea" style="width: 600px;" rows="8"  placeholder="费用包含" maxlength="200" show-word-limit></el-input>
                        </el-form-item>
                    </div>
                </div>
            </div>
            <div class="panel">
                <div class="header">附加信息</div>
                <div class="bd">
                    <div class="">
                        <el-form-item label="附加信息:" prop="addInfoList">
                            <el-button size="small" type="plain" @click="openDialog">添加</el-button>
                        </el-form-item>
                        <el-table border v-if="form.addInfoList.length" :data="form.addInfoList" style="width: 100%;margin-bottom: 15px" :header-cell-style="{background: '#DBEDF6'}">
                            <el-table-column prop="addInfoName" label="附加信息名称" header-align="center" align="center"></el-table-column>
                            <el-table-column prop="addDescribe" label="附加信息描述" header-align="center" align="center" min-width="100">
                            </el-table-column>
                            <el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
                                <template slot-scope="scope">
                                    <el-button type="text" size="small" @click="editSubjoin(scope.$index)">编辑</el-button>
                                    <el-button type="text" size="small" @click="deleteSubjoin(scope.$index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-form-item label="联系方式:" prop="telephone">
                            <el-input v-model="form.telephone" placeholder="请输入该资源的联系方式"></el-input>
                        </el-form-item>
                    </div>
                </div>
            </div>
            <div class="panel">
                <div class="header">有效期设置</div>
                <div class="bd">

                    <el-form-item label="日期设置:" prop="verifyType">
                        <el-radio v-model="form.verifyType" :label="0">有效期模式，无需用户指定使用日期</el-radio>
                        <el-radio v-model="form.verifyType" :label="1">使用日期模式，需用户指定使用日期，自所选日期起 <el-input type="number" v-model="form.verifyTypeNum" style="width: 100px"/> 内可使用</el-radio>
                    </el-form-item>
                    <el-divider />
                    <el-form-item label="库存设置:" prop="stockType">
                        <el-radio v-model="form.stockType" :label="0">无库存限制</el-radio>
                        <el-radio v-model="form.stockType" :label="1">有库存限制</el-radio>
                    </el-form-item>
                    <el-form-item label="库存模式:" prop="stockNumType" v-if="form.stockType == 1">
                        <el-radio v-model="form.stockNumType" :label="0">总库存 <el-input type="number" v-model="form.stockCountNum" placeholder="" style="width: 100px" /> 张</el-radio>
                        <el-radio v-model="form.stockNumType" :label="1" v-if="form.verifyType == 1">日库存</el-radio>
                    </el-form-item>
                    <el-divider />
                    <div class="calendar" v-if="form.verifyType === 1">
                        <div class="action">
                            <el-button @click="prev" class="bl" type="text" icon="el-icon-arrow-left"></el-button>
                            <el-button @click="next" class="br" type="text"><i class="el-icon-arrow-right el-icon--right"></i></el-button>
                        </div>
                        <div class="box" v-for="(item, idx) in calendar.data" :key="idx">
                            <div class="tit">
                                <span style="color: #fff">{{item.month}}</span>
                            </div>
                            <div class="cont">
                                <div class="week">
                                    <div class="it it-red">
                                        <sapn>日</sapn>
                                    </div>
                                    <div class="it">
                                        <sapn>一</sapn>
                                    </div>
                                    <div class="it">
                                        <sapn>二</sapn>
                                    </div>
                                    <div class="it">
                                        <sapn>三</sapn>
                                    </div>
                                    <div class="it">
                                        <sapn>四</sapn>
                                    </div>
                                    <div class="it">
                                        <sapn>五</sapn>
                                    </div>
                                    <div class="it it-red">
                                        <sapn>六</sapn>
                                    </div>
                                </div>
                                <div class="days">
                                    <div class="it" v-for="n in item.startSpace" :key="n">&nbsp;</div>
                                    <div class="it" v-for="(it, i) in item.days" :key="i+'-only'" @click="showPriceModal(it.checked,idx,i)">
                                        <div :class="currentDate.value === it.value ? 'bk_blue' :''">
                                            <div class="r">{{it.name}}</div>
                                            <template v-if="it.price" >
                                                <div class="r price">平台价：￥{{it.price.ctripPrice}}</div>
                                                <div class="r surplus">结算价：{{it.price.price}}</div>
                                                <div v-if="form.stockNumType === 1" class="r surplus">日库存：{{it.price.stockNum}}</div>
                                            </template>

                                        </div>
                                    </div>
                                    <!--<div class="it" v-for="n in item.endSpace" :key="n+1+'-only2'">&nbsp;</div>-->
                                </div>
                                <div class="resetCalendar">
                                    <el-button type="primary" @click="resetCalendar(item)">重置</el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <template v-if="form.verifyType=== 0">
                        <el-form-item label="有效期时间段:" prop="date">
                            <el-date-picker
                                    style="margin-bottom: 20px"
                                    v-model="form.date"
                                    placeholder="请选择有效期时间段"
                                    class="inputWidth"
                                    type="daterange" :default-time="['00:00:00','23:59:59']"
                                    value-format="yyyy-MM-dd"
                                    clearable
                                    start-placeholder="选择日期"
                                    end-placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="可用日期:" prop="weeks">
                            <el-checkbox-group  v-model="form.weeks">
                                <el-checkbox :label="1">周一</el-checkbox>
                                <el-checkbox :label="2">周二</el-checkbox>
                                <el-checkbox :label="3">周三</el-checkbox>
                                <el-checkbox :label="4">周四</el-checkbox>
                                <el-checkbox :label="5">周五</el-checkbox>
                                <el-checkbox :label="6">周六</el-checkbox>
                                <el-checkbox :label="0">周日</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                        <el-form-item label="不可用日期:" prop="notUseDateList">
                            <el-date-picker
                                    type="dates"
                                    value-format="yyyy-MM-dd"
                                    v-model="form.notUseDateList"
                                    placeholder="选择一个或多个日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="价格设置:" >
                            <el-col :span="6">
                                <el-form-item label="市场价(元):" prop="marketPrice">
                                    <el-input type="number" v-model="form.marketPrice" :min="0" placeholder="市场价（元）"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="结算价(元):" prop="price">
                                    <el-input type="number" v-model="form.price" :min="0"  placeholder="结算价（元）"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="平台价(元):" prop="ctripPrice">
                                    <el-input type="number" v-model="form.ctripPrice" :min="0"  placeholder="平台价（元）"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="游品库卖价(元):" prop="ypkPrice">
                                    <el-input type="number" v-model="form.ypkPrice" :min="0" placeholder="游品库卖价（元）"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                    </template>
                    <el-form-item label="佣金产品:" prop="enjoyRate">
                        <el-radio v-model="form.enjoyRate" :label="0">否</el-radio>
                        <el-radio v-model="form.enjoyRate" :label="1">是</el-radio>
                    </el-form-item>
                    <el-form-item label="分享文案:" prop="shareContent">
                        <el-input type="textarea" v-model="form.shareContent" style="width: 600px;" rows="8" ></el-input>
                    </el-form-item>
                </div>
            </div>
            <div class="panel">
                <div class="header">退款规则</div>
                <div class="bd">
                    <div class="fm-short">
                        <el-form-item label="退款设置:">
                            <el-radio v-model="form.refundNewType" :label="1">随时退</el-radio>
                            <el-radio v-model="form.refundNewType" :label="2">有条件退</el-radio>
                            <el-radio v-model="form.refundNewType" :label="3">不可退</el-radio>
                        </el-form-item>
                        <div style="border: 1px solid #eee;padding: 10px" v-if="form.refundNewType == 2">
                            <el-form-item label="时间限制:">
                                <el-select v-model="form.refundTimeType">
                                    <el-option :value="0" label="不限"/>
                                    <el-option :value="1" label="有效期开始前"/>
                                    <el-option :value="2" label="有效期开始后"/>
                                </el-select>&nbsp;&nbsp;
                                <template v-if="form.refundTimeType">
                                    <el-input type="number" v-model="form.refundTimeDay" :min="0" style="width: 100px"/> 天
                                    <el-input type="number" v-model="form.refundTimeHour" :min="0" :max="23"  style="width: 100px"/> 点
                                    <el-input type="number" v-model="form.refundTimeMinute" :min="0" :max="59"  style="width: 100px"/> 分
                                </template>&nbsp;&nbsp;
                            </el-form-item>
                            <el-form-item label="费用限制:" prop="refundCostType">
                                <el-select v-model="form.refundCostType">
                                    <el-option :value="0" label="无" />
                                    <el-option :value="1" label="%" />
                                    <el-option :value="2" label="元\张" />
                                    <el-option :value="3" label="元" />
                                </el-select>&nbsp;&nbsp;
                                <el-input v-if="form.refundCostType" type="number" v-model="form.refundCostValue" :min="0" style="width: 100px"/>
                            </el-form-item>
                        </div>
                        <el-form-item label="分批退款:" >
                            <el-radio v-model="form.refundPart" :label="0">只能一次退完</el-radio>
                            <el-radio v-model="form.refundPart" :label="1">可分批退</el-radio>
                        </el-form-item>
                    </div>
                </div>
            </div>
            <div class="panel">
                <div class="header">预定限制设置</div>
                <div class="bd">
                    <div class="fm-short" >
                        <el-row style="display: flex">
                            <el-form-item label="提前购买用户" prop="advanceBookingDays">
                                需在游玩前&nbsp;&nbsp;<el-input type="number" v-model="form.advanceBookingDays" :min="0" style="width: 100px"/>&nbsp;&nbsp;天&nbsp;&nbsp;
                            </el-form-item>
                            <el-form-item label-width="0px" prop="advanceBookingTimeHour">
                                <el-input type="number" v-model="form.advanceBookingTimeHour" :min="0" :max="23"  style="width: 100px"/>&nbsp;&nbsp;点&nbsp;&nbsp;
                            </el-form-item>
                            <el-form-item label-width="0px" prop="advanceBookingTimeMinute">
                                <el-input type="number" v-model="form.advanceBookingTimeMinute" :min="0" :max="59"  style="width: 100px"/>&nbsp;&nbsp;分前购买，方可使用
                            </el-form-item>
                        </el-row>
                        <el-form-item label="最晚可预订时间" prop="effectiveDays">
                            最晚可预订&nbsp;&nbsp;<el-input type="number" v-model="form.effectiveDays" placeholder="不限" :min="0" style="width: 100px"/>&nbsp;&nbsp;天
                        </el-form-item>
                        <el-form-item label="生效时长" prop="afterOrderToActiveTime">
                            购买后&nbsp;&nbsp;<el-input type="number" v-model="form.afterOrderToActiveTime" placeholder="不限" :max="59"  style="width: 100px"/>&nbsp;&nbsp;分钟，方可入园
                        </el-form-item>
                        <el-form-item label="游玩人信息" prop="needAllInfo">
                            <el-radio v-model="form.needAllInfo" :label="0">只需要一位游玩人</el-radio>
                            <el-radio v-model="form.needAllInfo" :label="1">需要全部游玩人</el-radio>
                        </el-form-item>
                        <div style="border: 1px solid #eee;padding: 10px;margin-bottom: 20px">
                            <el-form-item label="身份信息:" prop="customerTemplate">
                                <el-checkbox-group v-model="form.customerTemplate">
                                    <el-checkbox label="n">姓名</el-checkbox>
                                    <el-checkbox label="p">手机号</el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                            <el-form-item label="游玩人信息:" prop="customerTemplate">
                                <el-checkbox-group v-model="form.customerTemplate">
                                    <el-checkbox  label="i[1]">身份证</el-checkbox>
                                    <el-checkbox  label="i[2]">护照</el-checkbox>
                                    <el-checkbox  label="i[3]">学生证</el-checkbox>
                                    <el-checkbox  label="i[4]">军人证</el-checkbox>
                                    <el-checkbox  label="i[6]">驾驶证</el-checkbox>
                                    <el-checkbox  label="i[10]">港澳通行证</el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </div>
                        <el-form-item label="预订数量限制">每笔订单最少购买
                            <el-input type="number" v-model="form.minQuantity" :min="0" style="width: 100px"/> 张 最多购买
                            <el-input type="number" v-model="form.maxQuantity" placeholder="不限"  style="width: 100px"/> 张
                        </el-form-item>

                    </div>
                </div>
            </div>
            <div class="panel">
                <div class="header">入园方式</div>
                <div class="bd">
                    <div class="fm-short">
                        <el-form-item label="入园时间:">
                            <el-col :span="4">
                                <el-form-item prop="enterStartTime">
                                    <el-time-picker placeholder="开始时间" value-format="HH:mm:ss" v-model="form.enterStartTime" style="width: 100%;"></el-time-picker>
                                </el-form-item>
                            </el-col>
                            <el-col style="text-align: center" :span="1">-</el-col>
                            <el-col :span="4">
                                <el-form-item prop="enterEndTime">
                                    <el-time-picker placeholder="结束时间" value-format="HH:mm:ss" v-model="form.enterEndTime" style="width: 100%;"></el-time-picker>
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                        <el-form-item label="入园地址:" prop="enterAddress" style="width: 600px">
                            <el-input v-model="form.enterAddress" placeholder="具体到景区大门"></el-input>
                        </el-form-item>
                    </div>
                </div>
            </div>
            <el-button @click="submit(1)">保存并上架</el-button>
            <el-button type="primary" @click="submit(0)">保存，但不上架</el-button>
        </el-form>
        <el-dialog
                title="添加附加信息"
                :visible.sync="dialogVisible"
                width="30%">
            <el-form :model="subjoinForm" ref="subjoinForm">
                <el-form-item label="信息名称:" prop="addInfoName">
                    <el-input v-model.trim="subjoinForm.addInfoName" placeholder="信息名称" clearable class="inputWidth"></el-input>
                </el-form-item>
                <el-form-item label="信息描述:" prop="addDescribe">
                    <el-input type="textarea" v-model.trim="subjoinForm.addDescribe" placeholder="信息描述" clearable class="inputWidth"></el-input>
                </el-form-item>
                <div class="dialog-footer">
                  <el-button @click="resetForm('subjoinForm')">重 置</el-button>
                  <el-button type="primary" @click="submitSubjoinForm">确 定</el-button>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog title="售价设置" :visible.sync="dialog.visible" width="960px">
            <div slot="title"></div>
            <div>
                <div class="panel">
                    <div class="hd">售价设置</div>
                    <div class="bd">
                        <table cellspacing="0">
                            <tr >
                                <td>市场价（元）：</td>
                                <td>
                                    <el-input v-model="dialog.price.marketPrice" :min="1" size="small" style="width: 140px;" placeholder=""></el-input>
                                </td>
                                <td>平台价（元）：</td>
                                <td>
                                    <el-input v-model="dialog.price.ctripPrice" :min="1" size="small" style="width: 140px;" placeholder=""></el-input>
                                </td>
                            </tr>
                            <tr >
                                <td>结算价（元）：</td>
                                <td>
                                    <el-input v-model="dialog.price.price" :min="1" size="small" style="width: 140px;" placeholder=""></el-input>
                                </td>
                                <td>游品库卖价（元）：</td>
                                <td>
                                    <el-input v-model="dialog.price.ypkPrice" :min="1" size="small" style="width: 140px;" placeholder=""></el-input>
                                </td>
                            </tr>
                            <tr v-if="form.stockNumType === 1">
                                <td>日库存：</td>
                                <td>
                                    <el-input v-model="dialog.price.stockNum" :min="1" size="small" style="width: 140px;" placeholder=""></el-input>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="panel">
                    <div class="header">批量设置</div>
                    <div class="bd">
                        <el-form>
                            <el-form-item label="日期范围：">
                                <el-date-picker v-model="dialog.range"
                                                :default-value="dialog.defaultDate"
                                                unlink-panels
                                                @change="dateChange"
                                                type="daterange"
                                                :default-time="['00:00:00','23:59:59']"
                                                value-format="yyyy-MM-dd"
                                                range-separator="至"
                                                start-placeholder="开始日期"
                                                end-placeholder="结束日期">>

                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="设置星期：">
                                <el-checkbox-group v-model="dialog.weeks" size="small">
                                    <el-checkbox  :label="1" border>星期一</el-checkbox>
                                    <el-checkbox  :label="2" border>星期二</el-checkbox>
                                    <el-checkbox  :label="3" border>星期三</el-checkbox>
                                    <el-checkbox  :label="4" border>星期四</el-checkbox>
                                    <el-checkbox  :label="5" border>星期五</el-checkbox>
                                    <el-checkbox  :label="6" border>星期六</el-checkbox>
                                    <el-checkbox  :label="7" border>星期日</el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialog.visible = false">取 消</el-button>
            <el-button type="primary" @click="setPrice">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import TinymceEditor from '@/components/editor/editor'
import { formatDate } from '@/utils'
export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        activatedIsNeed: false,
        createdIsNeed: false
      },
      loading: false,
      form: {
        sourceFrom: '',
        cityId: '',
        spotId: '',
        supplierCode: '',
        peopleGroup: '',
        priceContain: '',
        weeks: [],
        date: [],
        resourceName: '',
        notUseDateList: [],
        refundNewType: '',
        refundPart: '',
        telephone: '',
        advanceBookingDays: '',
        advanceBookingTimeHour: '',
        advanceBookingTimeMinute: '',
        needAllInfo: '',
        minQuantity: '',
        maxQuantity: '',
        enterStartTime: '',
        enterEndTime: '',
        enterAddress: '',
        verifyType: '',
        stockType: '',
        stockCountNum: '',
        stockNumType: '0',
        addInfoList: [],
        verifyTypeNum: undefined,
        marketPrice: undefined,
        price: undefined,
        ctripPrice: undefined,
        ypkPrice: undefined,
        effectiveDays: undefined,
        afterOrderToActiveTime: undefined,
        refundTimeType: undefined,
        refundTimeDay: undefined,
        refundTimeHour: undefined,
        refundTimeMinute: undefined,
        refundCostType: undefined,
        refundCostValue: undefined,
        enjoyRate: 0,
        shareContent: undefined,
        validityDateEndDate: undefined,
        customerTemplate: ['n', 'p', 'i[1]'],
        priceCalendar: []
      },

      subjoinForm: {
        addDescribe: '',
        addInfoName: ''
      },
      rules: {
        sourceFrom: [{
          required: true,
          message: '请选择系统',
          trigger: 'blur'
        }],
        resourceName: [{
          required: true,
          message: '请输入产品名称',
          trigger: 'blur'
        }],
        cityId: [{
          required: true,
          message: '请选择景点所在的城市',
          trigger: 'blur'
        }],
        spotId: [{
          required: true,
          message: '请选择景区',
          trigger: 'blur'
        }],
        peopleGroup: [{
          required: true,
          message: '请选择门票票种',
          trigger: 'blur'
        }],
        priceContain: [{
          required: true,
          message: '请填写费用包含内容',
          trigger: 'blur'
        }],
        addInfoList: [{
          required: true,
          message: '请添加附加信息'
        }],
        telephone: [{
          required: true,
          message: '请输入该资源的联系方式',
          trigger: 'blur'
        }],
        advanceBookingDays: [{
          required: true,
          message: '请设置提前购买天数',
          trigger: 'blur'
        }],
        advanceBookingTimeHour: [{
          required: true,
          message: '请设置提前购买时间',
          trigger: 'blur'
        }],
        advanceBookingTimeMinute: [{
          required: true,
          message: '请设置提前购买时间',
          trigger: 'blur'
        }],
        effectiveDays: [{
          required: true,
          message: '请设置最晚可预订时间',
          trigger: 'blur'
        }],
        afterOrderToActiveTime: [{
          required: true,
          message: '请设置生效时长',
          trigger: 'blur'
        }],
        needAllInfo: [{
          required: true,
          message: '请选择游玩人信息',
          trigger: 'blur'
        }],
          enterStartTime: [{
              required: true,
              message: '请输入开始入园时间',
              trigger: 'blur'
          }],
        enterEndTime: [{
          required: true,
          message: '请输入结束入园时间',
          trigger: 'blur'
        }],
        enterAddress: [{
          required: true,
          message: '请填写入园地址',
          trigger: 'blur'
        }],
        verifyType: [{
          required: true,
          message: '请设置有效期',
          trigger: 'blur'
        }],
        stockType: [{
          required: true,
          message: '请设置库存',
          trigger: 'blur'
        }],
        stockNumType: [{
          required: true,
          message: '请设置库存模式',
          trigger: 'blur'
        }],
        date: [{
          required: true,
          message: '请设置有效期时间段',
          trigger: 'blur'
        }],
        weeks: [{
          required: true,
          message: '请设置可用日期',
          trigger: 'blur'
        }],
        marketPrice: [{
          required: true,
          message: '请设置市场价',
          trigger: 'blur'
        }],
        price: [{
          required: true,
          message: '请设置结算价',
          trigger: 'blur'
        }],
        ctripPrice: [{
          required: true,
          message: '请设置平台价',
          trigger: 'blur'
        }],
        ypkPrice: [{
          required: true,
          message: '请设置游品库卖价',
          trigger: 'blur'
        }],
        enjoyRate: [{
          required: true,
          message: '请设置是否可分享',
          trigger: 'blur'
        }]
      },
      selectDateList: [],

      currentIndex: '',
      data: {},
      date: undefined,
      supplierList: [],
      cityList: [],
      spotList: [],
      peoplesList: [],
      dialogVisible: false,
      active: {
        region: '',
        date: ['']
      },
      calendar: {
        cur: 0,
        vals: [],
        data: [{}]
      },
      datePrice: {
        price: []
      },
      dialog: {
        visible: false,
        price: {
          ctripPrice: undefined,
          date: undefined,
          marketPrice: undefined,
          price: undefined,
          stockNum: undefined,
          ypkPrice: undefined
        },
        range: [],
        weeks: [],
        defaultDate: undefined

      },
      currentDate: {}
    }
  },
  watch: {
    $route: {
      handler (to, form) {
        if (to.name == 'productEdit') {
          if (this.$route.params.id !== undefined) {
            this.id = this.$route.params.id
            const { source } = this.$route.params
            this.getSupplierList()
            this.getCityList()
            this.getPeoplesList()
            this.getSpotList('init')
            if (source === 'resource') {
              this.getResourceList()
            } else {
              this.getData()
            }
          }
        }
      },
      deep: true
    },
    date (newVal, oldVal) {
      if (newVal == null) {
        this.form.validityDateStartDate = null
        this.form.validityDateEndDate = null
      } else {
        this.form.validityDateStartDate = newVal[0]
        this.form.validityDateEndDate = newVal[1]
      }
    }
  },

  components: {
    TinymceEditor
  },
  created () {
    this.id = this.$route.params.id
    const { source } = this.$route.params
    this.getSupplierList()
    this.getCityList()
    this.getPeoplesList()
    this.getSpotList()
    if (source === 'resource') {
      this.getResourceList()
    } else {
      this.getData()
    }
    if (!this.id) {
      this.buildData()
    }
  },
  methods: {
    dateChange (date) {
      console.log('date=====', date)
    },
    buildData () {

      const m = this.calendar.cur
      // 获取当前前日期
      this.$set(this.calendar.data, 0, this.getDays(m))
    },
    prev () {
      this.calendar.cur -= 1
      this.buildData()
    },
    next () {
      this.calendar.cur += 1
      this.buildData()
    },
    getDays (offset) {

      // 偏移月
      const t = new Date()
      let y = t.getFullYear()
      let m = t.getMonth() + 1 + offset
      let d = null
      t.setMonth(m - 1)
      t.setDate(1)
      d = t.getDay() // 1号星期几
      t.setMonth(m)
      t.setDate(0)
      const ds = t.getDate() // 当月天数
      const days = []
      if (m > 12) {
        y += 1
        m -= 12
      }
      console.log("this.form.priceCalendar",this.form.priceCalendar);
      for (let i = 1; i <= ds; i++) {
        const month = y + '-' + m.toString().padStart(2, '0')
        const _date = month + '-' + i.toString().padStart(2, '0')
        var result = !!this.form.priceCalendar && this.form.priceCalendar.some(item => {
          if (item.groupName === month) {
            const flag = item.priceCalendarList.some((_item) => {
              if (_item.date === _date) {
                days.push({
                  name: i,
                  value: _date,
                  price: { ..._item },
                  checked: false,
                  week: (d + i - 1) % 7 ? (d + i - 1) % 7 : 7
                })
                return true
              }
            })
            return flag
          }
        })
        if (!result) {
          days.push({
            name: i,
            value: _date,
            checked: false,
            week: (d + i - 1) % 7 ? (d + i - 1) % 7 : 7
          })
        }
      }
      if (m > 12) {
        y += parseInt(m / 12)
        m = m % 12 == 0 ? 12 : m % 12
      } else if (m < 1) {
        y -= Math.ceil((Math.abs(m) + 1) / 12)
        m = m % 12 == 0 ? 12 : 12 + m % 12
      }
      return {
        month: y + '年' + m + '月',
        groupName: y + '-' + m.toString().padStart(2, '0'),
        startSpace: d,
        endSpace: 42 - (d + ds),
        startDate: y + '-' + m + '-01' + ' 00:00:00',
        endDate: y + '-' + m + '-' + ds + ' 23:59:59',
        checked: false,
        days: days,
        weekChecked: [false, false, false, false, false, false, false]
      }
    },

    changeStatus (value, index0, index1) {

    },
    setPrice () {
      this.formatEveryDay()
      this.dialog.visible = false
    },
    // 显示价格设置dialog
    showPriceModal (value, index0, index1) {
      this.currentDate = this.calendar.data[0].days[index1]
      console.log('currentDate', this.currentDate)
      this.initDialog(this.currentDate.value)
      this.dialog.visible = true
    },

    initDialog (defaultDate) {
      this.dialog = {
        visible: false,
        price: {
          ctripPrice: undefined,
          date: undefined,
          marketPrice: undefined,
          price: undefined,
          stockNum: undefined,
          ypkPrice: undefined
        },
        range: [defaultDate, defaultDate],
        weeks: [1,2,3,4,5,6,7]
      }
    },

    formatEveryDay () {
      const [start, end] = this.dialog.range
      const { weeks } = this.dialog
      const startTime = this.getDate(start)
      const endTime = this.getDate(end)
      while ((endTime.getTime() - startTime.getTime()) >= 0) {
        const year = startTime.getFullYear()
        const month = startTime.getMonth() + 1 < 10 ? '0' + (startTime.getMonth() + 1) : startTime.getMonth() + 1
        const day = startTime.getDate().toString().length == 1 ? '0' + startTime.getDate() : startTime.getDate()
        const date = year + '-' + month + '-' + day
        if (weeks.length > 0 && weeks.indexOf(startTime.getDay()) === -1) {
          startTime.setDate(startTime.getDate() + 1)
          continue
        }

        const monthIndex = this.form.priceCalendar ? this.form.priceCalendar.findIndex(item => item.groupName === year + '-' + month) : -1

        if (monthIndex === -1) {
          this.form.priceCalendar.push({
            groupName: year + '-' + month,
            priceCalendarList: [{ ...this.dialog.price,...{date} }]
          })
        } else {
          const flag = this.form.priceCalendar[monthIndex].priceCalendarList.some((item) => {
            if (item.date === date) {
              console.log('date', item)
              return true
            }
          })
          if (!flag) {
            this.form.priceCalendar[monthIndex].priceCalendarList.push({
              ...this.dialog.price, ...{ date: date }
            })
          }
        }
        startTime.setDate(startTime.getDate() + 1)
      }
      this.buildData()
    },

    getDate (datestr) {
      var temp = datestr.split('-')
      var date = new Date(temp[0], temp[1] - 1, temp[2])
      return date
    },

    getResourceList () {
      this.$http.get('/resource/generateResource', { params: { id: this.id } }).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        } else {
          res.data.customerTemplate = JSON.parse(res.data.customerTemplate)
          res.data.date = [res.data.validityDateStartDate, res.data.validityDateEndDate]
            if(!res.data.priceCalendar){
                res.data.priceCalendar = []
            }
          this.form = Object.assign(this.form, res.data)
          console.log('this.form', this.form)
          this.getSpotList('init')
          this.buildData()
        }
      }).catch(() => {})
    },
    getSupplierList () {
      this.$http.get('/form/getScenicSuppliers').then(res => {
        if (res.data.code !== 0) {
          return this.$message.error(res.data.msg)
        }
        this.supplierList = res.data.data
      })
    },
    getCityList () {
      this.$http.get('/form/getScenicCities').then(res => {
        if (res.data.code !== 0) {
          return this.$message.error(res.data.msg)
        }
        this.cityList = res.data.data
      })
    },
    getSpotList (type) {
      console.log('this.form.cityId', this.form.cityId)
      if (this.form.cityId) {
        this.$http.get('/spot/searchSpot', { params: { cityId: this.form.cityId } }).then(res => {
          if (res.data.code !== 0) {
            return this.$message.error(res.data.msg)
          }
          if (!type) {
            this.form.spotId = ''
          }
          this.spotList = res.data.data
        })
      }
    },
    getPeoplesList () {
      this.$http.get('/form/getScenicPeoples').then(res => {
        if (res.data.code !== 0) {
          return this.$message.error(res.data.msg)
        }
        console.log('r===============', res)
        this.peoplesList = res.data.data
      })
    },
    getData () {
      this.$http.get('/resource/getResourceInfo', { params: { id: this.id } }).then(res => {
        if (res.data.code !== 0) {
          return this.$message.error(res.data.msg)
        }
        res.data.data.customerTemplate = JSON.parse(res.data.data.customerTemplate)
        res.data.data.date = [res.data.data.validityDateStartDate, res.data.data.validityDateEndDate]
        if(!res.data.data.priceCalendar){
          res.data.data.priceCalendar = []
        }
        this.form = Object.assign(this.form, res.data.data)
        console.log(' this.form===', this.form)
        this.getSpotList('init')
        this.buildData()
      })
    },
    openDialog () {
      this.dialogVisible = true
      this.currentIndex = ''
      this.$nextTick(() => {
        this.subjoinForm = {
          addDescribe: '',
          addInfoName: ''
        }
        console.log('this.subjoinForm', this.subjoinForm)
      })
    },
    submitSubjoinForm () {
      if (this.form.addInfoList[this.currentIndex]) {
        this.form.addInfoList.splice(this.currentIndex, 1, { ...this.subjoinForm })
      } else {
        this.form.addInfoList.push({ ...this.subjoinForm })
      }
      this.dialogVisible = false
    },
    editSubjoin (index) {
      this.currentIndex = index
      this.dialogVisible = true

      this.$nextTick(() => {
        this.subjoinForm = { ...this.form.addInfoList[this.currentIndex] }
      })
    },
    deleteSubjoin (index) {
      this.form.addInfoList.splice(index, 1)
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    resetCalendar (v) {
      this.$confirm('是否确认重置本月所有价格?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
            if(this.form.priceCalendar.length) {
              const calendarIndex = this.form.priceCalendar.findIndex((item) => item.groupName === v.groupName)
              if (calendarIndex !== -1) {
                this.form.priceCalendar[calendarIndex].priceCalendarList = []
                this.buildData()
              }
              this.$message({
                message: '重置成功',
                type: 'success'
              })
            }
        })
    },
    submit (status) {
      const form = this.form
      let priceCalendar = []
      if (form.verifyType === 1 && !!this.form.priceCalendar && !this.form.priceCalendar.length) {
        this.form.priceCalendar.map((item) => {
          priceCalendar = priceCalendar.concat(item.priceCalendarList)
        })
      }
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false
        }
        if (form.verifyType === 1) {
            if (!form.verifyTypeNum) {
              this.$message.error('请输入日期中的所选日期限制')
              return
            }
        }
        this.$http.post('/resource/saveOrUpdateResource', { ...form, ...{ customerTemplate: JSON.stringify(form.customerTemplate), resourceStatus: status, priceCalendar } })
          .then(res => {
            if (res.data.code !== 0) {
              return this.$message.error(res.data.msg)
            }
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.closeCurrentTab()
            this.loading = false
          })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
    .box{
        padding: 15px;
        background: #fff;
    }
    .phone {
        min-width: 120px;
    }

    .dialog {
        .tips {
            background: #f5f5f5;
            padding: 20px;
        }

        .upload {
            padding: 20px 0;
        }
    }

    .header,.hd {
        padding: 0 20px;
        height: 50px;
        line-height: 50px;
        font-size: 16px;
        font-weight: bold;
        color: #333;
        border-bottom: 1px solid #e9e9e9;
        margin-bottom: 15px;
        span {
            font-size: 12px;
            color: #999;
            font-weight: normal;
            margin-left: 10px;
        }
    }

    .hd::before {
        content: "*";
        color: #f56c6c;
        margin-right: 4px;
    }

    .contact-item {
        display: flex;
        margin-bottom: 10px;

        .it {
            flex: 1;
        }

        .it2 {
            flex: 2;
            margin: 0 20px;
        }

        .it3 {
            width: 30px;
            margin-left: 20px;
        }
    }
    .dialog-footer{
        text-align: center;
    }
    .calendar {
        display: flex;
        position: relative;

        .action {
            position: absolute;
            top: 0;
            width: 100%;
            padding: 15px 30px;
            .bl {
                float: left;
                color: #fff;
            }

            .br {
                float: right;
                color: #fff;
            }
        }

        .bk_blue {
            height: 100%;
            color: #fff;
            background-color: #407ae6;
        }

        .box {
            flex: 1;
            margin-right: 10px;

            &:last-child {
                margin-right: 0;
            }

            .tit {
                text-align: center;
                height: 42px;

                line-height: 42px;
                background: #17B3A3;
                .el-checkbox{
                    color: #fff;
                }
            }

            .cont {
                font-size: 12px;

                .week {
                    display: flex;
                    border-top: 1px solid #e7e8eb;
                    border-left: 1px solid #e7e8eb;

                    .it {
                        width: 14.28%;
                        padding: 4px 0;
                        background: #eff0f3;
                        border-right: 1px solid #e7e8eb;
                        text-align: center;

                        &.it-red ::v-deep .el-checkbox__label {
                            color: #fe2724;
                        }
                    }
                }

                .days {
                    display: flex;
                    flex-wrap: wrap;
                    /*border-top: 1px solid #e7e8eb;*/
                    /*border-left: 1px solid #e7e8eb;*/
                    border: 1px solid #e7e8eb;

                    .it {
                        cursor: pointer;
                        width: 14.28%;
                        border-right: 1px solid #e7e8eb;
                        border-bottom: 1px solid #e7e8eb;
                        text-align: center;
                        height: 75px;
                        display: flex;
                        flex-direction: column;

                        /*padding: 6px 0;*/
                        .r {
                            flex: 1;
                        }

                        &.active {
                            background: #3753c6;
                            color: #fff;
                        }

                        &:nth-of-type(7n + 7) {
                            color: #fe2724;
                        }

                        &:nth-of-type(7n + 1) {
                            color: #fe2724;
                        }

                        .surplus,
                        .price {
                            font-size: 10px;
                            color: #000;
                        }
                    }
                }
                .resetCalendar{
                    text-align: right;
                    margin:10px
                }
            }
        }
    }
</style>
